package com.isyscore.os.metadata.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.isyscore.boot.login.LoginUserManagerImpl;
import com.isyscore.os.metadata.model.vo.DataQueryVO;
import com.isyscore.os.metadata.service.DataBuildService;
import com.isyscore.os.metadata.service.TaskService;
import com.isyscore.os.permission.entity.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * @author fjZheng
 * @version 1.0
 * @date 2020/12/1 9:43
 */
@RestController
@Api(tags = "数据建设")
@RequestMapping("${api-full-prefix:}/dataBuild")
public class DataBuildController {
    @Resource
    private DataBuildService dataBuildService;

    @Resource
    private TaskService taskService;

    @Autowired
    private LoginUserManagerImpl loginUserManager;

    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("data-builder-pool-%d").build();


    private ExecutorService fixedThreadPool = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, Runtime.getRuntime().availableProcessors() * 40,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(Runtime.getRuntime().availableProcessors() * 20), namedThreadFactory);


    @ApiOperation("执行sql")
    @PostMapping("/sql")
    public JSONObject execute(@RequestBody DataQueryVO dataQueryVO) {
        String taskId = taskService.creatTask(1L, TimeUnit.HOURS, null);
        JSONObject rst = new JSONObject();
        rst.put("taskId", taskId);
        LoginVO current = loginUserManager.getCurrentLoginUser();
        fixedThreadPool.submit(() -> {
            loginUserManager.setThreadLocalLoginUser(current);
            dataBuildService.executeSQL(dataQueryVO, taskId);
        });
        return rst;
    }

}
